import React, { useState, useEffect } from 'react';
import { Card, Row, Col, Spin, Alert, Typography, Button, Space, InputNumber, Form, Collapse, Input, Select } from 'antd';
import { ArrowLeftOutlined, ReloadOutlined, FilterOutlined } from '@ant-design/icons';
import ReactECharts from 'echarts-for-react';
import { stockApi } from '../services/stockApi';

const { Title } = Typography;
const { Panel } = Collapse;
const { Group } = Input;
const { Option } = Select;

const StockCharts = ({ onBack }) => {
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [stockData, setStockData] = useState([]);
  const [filteredData, setFilteredData] = useState([]);
  const [filterVisible, setFilterVisible] = useState(false);
  const [selectedYear, setSelectedYear] = useState(new Date().getFullYear()); // 默认当前年份
  
  // 生成年份选项（当前年份及前5年）
  const generateYearOptions = () => {
    const currentYear = new Date().getFullYear();
    const years = [];
    for (let i = 0; i <= 5; i++) {
      years.push(currentYear - i);
    }
    return years;
  };
  
  // 筛选条件状态
  const [filters, setFilters] = useState({
    minPrice: null,
    maxPrice: null,
    minDividend: null,
    maxDividend: null,
    minShares: null,
    maxShares: null
  });

  // 应用筛选条件
  const applyFilters = () => {
    let filtered = [...stockData];
    
    // 应用价格范围筛选
    if (filters.minPrice !== null) {
      filtered = filtered.filter(item => item.max_price >= filters.minPrice);
    }
    if (filters.maxPrice !== null) {
      filtered = filtered.filter(item => item.max_price <= filters.maxPrice);
    }
    
    // 应用股息范围筛选
    if (filters.minDividend !== null) {
      filtered = filtered.filter(item => item.dividend >= filters.minDividend);
    }
    if (filters.maxDividend !== null) {
      filtered = filtered.filter(item => item.dividend <= filters.maxDividend);
    }
    
    // 应用流通量范围筛选
    if (filters.minShares !== null) {
      filtered = filtered.filter(item => item.liqa_share >= filters.minShares * 100000000);
    }
    if (filters.maxShares !== null) {
      filtered = filtered.filter(item => item.liqa_share <= filters.maxShares * 100000000);
    }
    
    setFilteredData(filtered);
  };
  
  // 重置筛选条件
  const resetFilters = () => {
    setFilters({
      minPrice: null,
      maxPrice: null,
      minDividend: null,
      maxDividend: null,
      minShares: null,
      maxShares: null
    });
    setFilteredData(stockData);
  };
  
  // 当筛选条件变化时，自动应用筛选
  useEffect(() => {
    if (stockData.length > 0) {
      applyFilters();
    }
  }, [filters, stockData]);
  
  // 获取股票数据
  const fetchStockData = async () => {
    try {
      setLoading(true);
      setError(null);
      const data = await stockApi.getAllStocks(selectedYear);
      setStockData(data || []);
      setFilteredData(data || []); // 初始化筛选数据为全部数据
    } catch (err) {
      console.error('获取股票数据失败:', err);
      // 如果API请求失败，使用模拟数据
      console.log('使用模拟数据进行演示');
      const mockData = [
        {
          stock_no: '000001',
          stock_market: 'sz',
          name: '平安银行',
          max_price: 15.68,
          dividend: 0.35,
          liqa_share: 19405918110,
          open_price: 14.20,
          close_price: 14.85
        },
        {
          stock_no: '000002',
          stock_market: 'sz',
          name: '万科A',
          max_price: 18.95,
          dividend: 0.85,
          liqa_share: 9639354645,
          open_price: 17.50,
          close_price: 18.20
        },
        {
          stock_no: '600036',
          stock_market: 'sh',
          name: '招商银行',
          max_price: 35.68,
          dividend: 1.25,
          liqa_share: 20672387665,
          open_price: 34.20,
          close_price: 34.85
        },
        {
          stock_no: '600519',
          stock_market: 'sh',
          name: '贵州茅台',
          max_price: 1685.68,
          dividend: 21.75,
          liqa_share: 1256197800,
          open_price: 1650.20,
          close_price: 1670.85
        },
        {
          stock_no: '000858',
          stock_market: 'sz',
          name: '五粮液',
          max_price: 185.68,
          dividend: 2.55,
          liqa_share: 3868147965,
          open_price: 180.20,
          close_price: 182.85
        },
        {
          stock_no: '600276',
          stock_market: 'sh',
          name: '恒瑞医药',
          max_price: 65.68,
          dividend: 0.95,
          liqa_share: 4145938765,
          open_price: 62.20,
          close_price: 63.85
        },
        {
          stock_no: '300750',
          stock_market: 'sz',
          name: '宁德时代',
          max_price: 285.68,
          dividend: 3.25,
          liqa_share: 2331404165,
          open_price: 280.20,
          close_price: 282.85
        },
        {
          stock_no: '002415',
          stock_market: 'sz',
          name: '海康威视',
          max_price: 45.68,
          dividend: 0.75,
          liqa_share: 9338144165,
          open_price: 42.20,
          close_price: 43.85
        }
      ];
      setStockData(mockData);
      setFilteredData(mockData); // 初始化筛选数据为全部数据
      setError(`注意：当前使用模拟数据 (${selectedYear}年)，请确保后端服务已启动以获取真实数据`);
    } finally {
      setLoading(false);
    }
  };

  // 组件挂载时获取数据
  useEffect(() => {
    fetchStockData();
  }, [selectedYear]);

  // 准备股息与最高价的图表数据
  const getDividendPriceChartOption = () => {
    // 过滤有效数据
    const validData = filteredData.filter(item => 
      item.dividend && item.dividend > 0 && 
      item.max_price && item.max_price > 0
    );

    // 转换数据为图表需要的格式 [股息, 最高价, 股票名称]
    const chartData = validData.map(item => [
      item.dividend,
      item.max_price,
      item.name || `${item.stock_market}.${item.stock_no}`
    ]);

    return {
      title: {
        text: '股息与最高价关系图',
        left: 'center'
      },
      tooltip: {
        trigger: 'item',
        formatter: function(params) {
          return `${params.value[2]}<br/>股息: ¥${params.value[0]}<br/>最高价: ¥${params.value[1]}`;
        }
      },
      xAxis: {
        name: '股息',
        type: 'value',
        nameLocation: 'middle',
        nameGap: 30,
        axisLabel: {
          formatter: '¥{value}'
        }
      },
      yAxis: {
        name: '最高价',
        type: 'value',
        nameLocation: 'middle',
        nameGap: 30,
        axisLabel: {
          formatter: '¥{value}'
        }
      },
      series: [{
        name: '股票',
        type: 'scatter',
        data: chartData,
        symbolSize: function (data) {
          // 根据最高价调整点的大小
          return Math.min(Math.max(data[1] / 5, 5), 20);
        },
        itemStyle: {
          color: '#1890ff'
        },
        emphasis: {
          focus: 'series',
          label: {
            show: true,
            position: 'top',
            formatter: function(params) {
              return params.value[2];
            }
          }
        }
      }]
    };
  };

  // 准备流通量与最高价的图表数据
  const getSharesPriceChartOption = () => {
    // 过滤有效数据
    const validData = filteredData.filter(item => 
      item.liqa_share && item.liqa_share > 0 && 
      item.max_price && item.max_price > 0
    );

    // 转换数据为图表需要的格式 [流通量(亿股), 最高价, 股票名称]
    const chartData = validData.map(item => [
      item.liqa_share / 100000000, // 转换为亿股
      item.max_price,
      item.name || `${item.stock_market}.${item.stock_no}`
    ]);

    return {
      title: {
        text: '流通量与最高价关系图',
        left: 'center'
      },
      tooltip: {
        trigger: 'item',
        formatter: function(params) {
          return `${params.value[2]}<br/>流通量: ${params.value[0].toFixed(2)}亿股<br/>最高价: ¥${params.value[1]}`;
        }
      },
      xAxis: {
        name: '流通量（亿股）',
        type: 'value',
        nameLocation: 'middle',
        nameGap: 30,
        axisLabel: {
          formatter: '{value}'
        }
      },
      yAxis: {
        name: '最高价',
        type: 'value',
        nameLocation: 'middle',
        nameGap: 30,
        axisLabel: {
          formatter: '¥{value}'
        }
      },
      series: [{
        name: '股票',
        type: 'scatter',
        data: chartData,
        symbolSize: function (data) {
          // 根据流通量调整点的大小
          return Math.min(Math.max(data[0] / 2, 5), 20);
        },
        itemStyle: {
          color: '#52c41a'
        },
        emphasis: {
          focus: 'series',
          label: {
            show: true,
            position: 'top',
            formatter: function(params) {
              return params.value[2];
            }
          }
        }
      }]
    };
  };

  return (
    <div>
      <div style={{ marginBottom: 16, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <Space>
          <Button 
            icon={<ArrowLeftOutlined />} 
            onClick={onBack}
          >
            返回
          </Button>
          <Title level={3} style={{ margin: 0 }}>股票数据分析图表</Title>
        </Space>
        <Space>
          <Select
            value={selectedYear}
            onChange={setSelectedYear}
            style={{ width: 100 }}
            placeholder="选择年份"
          >
            {generateYearOptions().map(year => (
              <Option key={year} value={year}>{year}年</Option>
            ))}
          </Select>
          <Button 
            icon={<FilterOutlined />} 
            onClick={() => setFilterVisible(!filterVisible)}
          >
            {filterVisible ? '隐藏筛选' : '显示筛选'}
          </Button>
          <Button 
            icon={<ReloadOutlined />} 
            onClick={fetchStockData}
            loading={loading}
          >
            刷新数据
          </Button>
        </Space>
      </div>

      {filterVisible && (
        <Card style={{ marginBottom: 16 }}>
          <Form layout="vertical">
            <Title level={4}>数据筛选范围</Title>
            <Row gutter={[16, 16]}>
              <Col xs={24} sm={12} md={8}>
                <Form.Item label="最高价范围 (元)">
                  <Input.Group compact>
                    <InputNumber
                      style={{ width: '50%' }}
                      placeholder="最低价"
                      value={filters.minPrice}
                      onChange={(value) => setFilters({...filters, minPrice: value})}
                      min={0}
                      step={0.01}
                    />
                    <InputNumber
                      style={{ width: '50%' }}
                      placeholder="最高价"
                      value={filters.maxPrice}
                      onChange={(value) => setFilters({...filters, maxPrice: value})}
                      min={0}
                      step={0.01}
                    />
                  </Input.Group>
                </Form.Item>
              </Col>
              <Col xs={24} sm={12} md={8}>
                <Form.Item label="股息范围 (元)">
                  <Input.Group compact>
                    <InputNumber
                      style={{ width: '50%' }}
                      placeholder="最低股息"
                      value={filters.minDividend}
                      onChange={(value) => setFilters({...filters, minDividend: value})}
                      min={0}
                      step={0.01}
                    />
                    <InputNumber
                      style={{ width: '50%' }}
                      placeholder="最高股息"
                      value={filters.maxDividend}
                      onChange={(value) => setFilters({...filters, maxDividend: value})}
                      min={0}
                      step={0.01}
                    />
                  </Input.Group>
                </Form.Item>
              </Col>
              <Col xs={24} sm={12} md={8}>
                <Form.Item label="流通量范围 (亿股)">
                  <Input.Group compact>
                    <InputNumber
                      style={{ width: '50%' }}
                      placeholder="最低流通量"
                      value={filters.minShares}
                      onChange={(value) => setFilters({...filters, minShares: value})}
                      min={0}
                      step={0.01}
                    />
                    <InputNumber
                      style={{ width: '50%' }}
                      placeholder="最高流通量"
                      value={filters.maxShares}
                      onChange={(value) => setFilters({...filters, maxShares: value})}
                      min={0}
                      step={0.01}
                    />
                  </Input.Group>
                </Form.Item>
              </Col>
            </Row>
            <Space>
              <Button onClick={resetFilters}>重置筛选</Button>
              <span style={{ color: '#666' }}>
                当前显示: {filteredData.length} / {stockData.length} 只股票
              </span>
            </Space>
          </Form>
        </Card>
      )}

      {error && (
        <Alert
          message="错误"
          description={error}
          type="error"
          showIcon
          style={{ marginBottom: 16 }}
        />
      )}

      <Spin spinning={loading}>
        <Row gutter={[16, 16]}>
          <Col xs={24} lg={12}>
            <Card>
              <ReactECharts 
                option={getDividendPriceChartOption()} 
                style={{ height: '500px' }}
                notMerge={true}
                lazyUpdate={true}
              />
            </Card>
          </Col>
          <Col xs={24} lg={12}>
            <Card>
              <ReactECharts 
                option={getSharesPriceChartOption()} 
                style={{ height: '500px' }}
                notMerge={true}
                lazyUpdate={true}
              />
            </Card>
          </Col>
        </Row>
        
        <Card style={{ marginTop: 16 }}>
          <Title level={4}>图表说明</Title>
          <Row gutter={[16, 16]}>
            <Col xs={24} md={12}>
              <p><strong>股息与最高价关系图：</strong></p>
              <ul>
                <li>横轴表示股息金额</li>
                <li>纵轴表示股票最高价</li>
                <li>点的大小与最高价成正比</li>
                <li>鼠标悬停可查看具体股票信息</li>
              </ul>
            </Col>
            <Col xs={24} md={12}>
              <p><strong>流通量与最高价关系图：</strong></p>
              <ul>
                <li>横轴表示流通量（亿股）</li>
                <li>纵轴表示股票最高价</li>
                <li>点的大小与流通量成正比</li>
                <li>鼠标悬停可查看具体股票信息</li>
              </ul>
            </Col>
          </Row>
        </Card>
      </Spin>
    </div>
  );
};

export default StockCharts;